Create a Token-based Lambda Authorizer

Create a Token-based Lambda Authorizer

Clock Icon2024.02.18

Introduction

I tried creating a lambda authorier for the API Gateway. Lambda authorizer is a useful feature to implement custom authorization scheme. It uses a bearer token authentication strategy such as OAuth or SAML.

This blog-post will walk you through creating a token-based Lambda Authorizer for API Gateway, allowing you to control access to your resources based on bearer tokens.

Workflow 

  1. Client Request: The client initiates a request to API methods (e.g., GET, POST, PUT, DELETE).
  2. API Gateway Invocation: API Gateway triggers the configured Lambda Authorizer.
  3. Authorization Check: The Lambda Authorizer verifies the caller's identity using the provided bearer token.
  4. IAM Policy Generation: Based on the token's validity, the Lambda Authorizer generates an IAM policy.
  5. Access Evaluation: API Gateway evaluates the IAM policy and either allows or denies access to the requested resource.

Types of Lambda Authorizer

  • Token-based lambda authorizer: Utilizes bearer tokens for authentication, such as OAuth 2.0 or JWT-based systems.
  • Request parameter-based lambda authorizer: Authentication information is passed directly within the request parameters, like query parameters or form data.

Prerequisites 

  • AWS account with appropriate permissions.
  • Resources and methods configured in API Gateway.

Creating a Token-based Lambda Authorizer

Step 1:  Create a lambda function for Authentication

This function will serve as custom authorizer. We can write the authentication and authorization logic inside this function, such as token validation or user role checks.

Below is the sample code for simple authorization

// A simple token-based authorizer example to demonstrate how to use an authorization token
// to allow or deny a request. In this example, the caller named 'user' is allowed to invoke
// a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke
// the request if the token value is 'deny'. If the token value is 'unauthorized' or an empty
// string, the authorizer function returns an HTTP 401 status code. For any other token value,
// the authorizer returns an HTTP 500 status code.
// Note that token values are case-sensitive.

export const handler = function (event, context, callback) {
  var token = event.authorizationToken
  switch (token) {
    case 'allow':
      callback(null, generatePolicy('user', 'Allow', event.methodArn))
      break
    case 'deny':
      callback(null, generatePolicy('user', 'Deny', event.methodArn))
      break
    case 'unauthorized':
      callback('Unauthorized') // Return a 401 Unauthorized response
      break
    default:
      callback('Error: Invalid token') // Return a 500 Invalid token response
  }
}

// Help function to generate an IAM policy
var generatePolicy = function (principalId, effect, resource) {
  var authResponse = {}
  authResponse.principalId = principalId
  if (effect && resource) {
    var policyDocument = {}
    policyDocument.Version = '2012-10-17'
    policyDocument.Statement = []
    var statementOne = {}
    statementOne.Action = 'execute-api:Invoke'
    statementOne.Effect = effect
    statementOne.Resource = resource
    policyDocument.Statement[0] = statementOne
    authResponse.policyDocument = policyDocument
  } // Optional output with custom properties of the String, Number or Boolean type.
  authResponse.context = {
    stringKey: 'stringval',
    numberKey: 123,
    booleanKey: true,
  }
  return authResponse
}

Step 2: Configure API Gateway Authorizer

Navigate to the API Gateway console and select your API. Under the "Authorizers" section, create a new authorizer and choose "Lambda Function" type. Specify the ARN of the Lambda function created in Step 1.

Step 3: Attach Authorizer to API endpoint

Select the desired API endpoint and configure it to use the authorizer created in the previous step. You can choose to enable the authorizer for all methods or specific methods based on your application's requirements.

Step 4: Test Authorization

Test the authorization flow by making requests to the secured API endpoint. Ensure that the Lambda authorizer function returns the appropriate IAM policy based on the provided authentication credentials or other criteria.
 

Conclusion

API Gateway Lambda Authorizers offer a robust solution for implementing secure authentication and authorization in serverless applications. By leveraging Lambda functions for custom authorization logic, you can ensure that only authenticated and authorized users access your API endpoints. Incorporate Lambda Authorizers into your serverless architecture to enhance security, centralize management, and scale effectively.

 

 

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.